/**
 * JSLoader js异步加载
 * @param  {string} url load加载url
 * @param  {function} callback
 */
function jsLoader(url, callback, id) {
    if (!url || url.length === 0) {
        throw new Error('argument "url" is required !');
    }
    const head = document.getElementsByTagName('head')[0]
    const script = document.createElement('script')
    const scriptId = id || url.toString()

    if (document.getElementById(scriptId)) {
        callback && typeof callback === 'function' && callback()
        return false
    }
    script.id = scriptId
    script.setAttribute('type', 'text/javascript')
    script.setAttribute('src', url)

    if (callback) {
        /* eslint no-multi-assign: 'off'*/
        script.onload = script.onreadystatechange = function () {
            if (script.ready) {
                return false
            }
            if (!script.readyState || script.readyState === 'loaded' || script.readyState === 'complete') {
                script.ready = true
                if (typeof callback === 'function') {
                    callback()
                }
                //IE内存泄露
                script.onload = null;
                script.onreadystatechange = null
                if (head && script.parentNode) {
                    head.removeChild(script);
                }
            }
            return true
        }
    }
    head.appendChild(script)
    return true
}

export default jsLoader
